<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

// 本着严谨的原则，5.0版本默认情况下会对任何错误（包括警告错误）抛出异常，如果不希望如此严谨的抛出异常，可以在应用公共函数文件中或者配置文件中使用error_reporting方法设置错误报错级别
// 异常错误报错级别,（请注意，在入口文件中设置是无效的）
error_reporting(E_ALL & ~E_NOTICE);
define('NOW_TIME', $_SERVER['REQUEST_TIME']);
use think\Db;

/**
 * 模拟tab产生空格
 * @param int $step
 * @param string $string
 * @param int $size
 * @return string
 */
function tab($step = 1, $string = ' ', $size = 4)
{
    return str_repeat($string, $size * $step);
}
function logs($name, $data) {

    file_put_contents(ROOT_PATH . 'log/' . $name . "_log.txt", var_export($data, TRUE), FILE_APPEND);
    file_put_contents(ROOT_PATH . 'log/' . $name . "2_log.txt", print_r($data, TRUE), FILE_APPEND);
    file_put_contents(ROOT_PATH . 'log/' . $name . "_log.txt", "\r\n", FILE_APPEND);
    file_put_contents(ROOT_PATH . 'log/' . $name . "2_log.txt", "\r\n", FILE_APPEND);
}
function send_stomp($topic, $data, $stomp_service = 'tcp://127.0.0.1:61613') {
    /**
      $stomp = new \Stomp('tcp://127.0.0.1:61613');
      $obj = new \Stdclass();
      //下面这些数据，实际中是用户通过前端页面post来的，这里只做演示
      $obj->url = Url::build('admin/student_statistics_api/statistics',null,null,true);
      $obj->user_id = $user_id;
      $obj->date = $date;
      $obj->key = $this->job_key;
      //发送一个注册消息到队列
      $stomp->send($this->job_key, json_encode($obj), array('persistent'=>"true"));
     * */
    $stomp =   new \FuseSource\Stomp\Stomp($stomp_service);
    $stomp->connect();
//    $obj = (object) $data;
    $re=$stomp->send($topic, json_encode($data), array('persistent' => true),TRUE);
    echo $re;
    return $re;
}

/**
 * 获取当前页面完整URL地址
 */
function get_url() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self . (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '') . $relate_url;
}
function get_host(){
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    return $sys_protocal .(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '');
}
/**
 * 获取微信操作对象
 * @staticvar array $wechat
 * @param type $type
 * @return WechatReceive
 */
function &load_wechat( $get_type = null ,$type = 'Oauth') {
    !class_exists('Wechat\Loader', FALSE) && Vendor('Wechat.Loader');
    static $wechat = array();
    $index = md5(strtolower($type));
    if (!isset($wechat[$index])) {

        $model = Db::name('WechatConfig');
        $map = [];
        if ($get_type) {
            $map['config_key'] =$get_type;
            $model->where($map);
        }
        // 从数据库查询配置参数
        $config = $model->field('token,appid,appsecret,encodingaeskey,mch_id,partnerkey,ssl_cer,ssl_key,qrc_img')->find();
        // 设置SDK的缓存路径
        $config['cachepath'] = CACHE_PATH . 'Data/';
        $wechat[$index] = \Wechat\Loader::get_instance($type, $config);
    }
    return $wechat[$index];
}

function get_wx_config($get_type = "base") {
    $model = Db::name('WechatConfig');
    $map = [];
    if ($get_type) {
        $map['config_key'] = config("weixin.$get_type");
        $model->where($map);
    } else if (config("weixin.base")) {
        $map['config_key'] = config("weixin.base");
        $model->where($map);
    }
    // 从数据库查询配置参数
    $config = $model->field('token,appid,appsecret,encodingaeskey,mch_id,partnerkey,ssl_cer,ssl_key,qrc_img')->find();
    logs('get_wx_config',$model->getLastSql());
    logs('get_wx_config',$config);
    return $config;
}
/**
 * 节点遍历
 *
 * @param        $list
 * @param string $pk
 * @param string $pid
 * @param string $child
 * @param int    $root
 *
 * @return array
 */
function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    // 创建Tree
    $tree = [];
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $data) {
            if ($data instanceof \think\Model) {
                $list[$key] = $data->toArray();
            }
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            if (!isset($list[$key][$child])) {
                $list[$key][$child] = [];
            }
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }

    return $tree;
}
function getPraent($son_id, $_pids, $tree_table = "tp_driver_rank_tree") {
    $map['parent_id'] = array('in', $_pids);
    $map['depth'] = array('neq', 0);
    $map['son_id'] = $son_id;
    $re = Db::table($tree_table)->where($map)->order('depth asc')->find();
//        logs("tree_table",Db::table($tree_table)->getLastSql());
    if ($re) {
        return $re['parent_id'];
    }
    return;
}
/**
 * 统一密码加密方式，如需变动直接修改此处
 * @param $password
 * @return string
 */
function password_hash_tp($password)
{
    return hash("md5", trim($password));
}
//阿里云policy形式 gmt_iso8601函数
function gmt_iso8601($time) {
    $dtStr = date("c", $time);
    $mydatetime = new DateTime($dtStr);
    $expiration = $mydatetime->format(DateTime::ISO8601);
    $pos = strpos($expiration, '+');
    $expiration = substr($expiration, 0, $pos);
    return $expiration."Z";
}
//阿里云oss policy形式
function ali_oss($dir = 'user-dir/'){

    $id= 'LTAIGd5Jkwuirwku';
    $key= 'qt7YM8kRhmjNjoJbQ1fsP3ianW3sw4';
    $host = 'https://huaer-video.oss-cn-beijing.aliyuncs.com';

    $now = time();
    $expire = 30; //设置该policy超时时间是30s. 即这个policy过了这个有效时间，将不能访问
    $end = $now + $expire;
    $expiration = gmt_iso8601($end);


    //最大文件大小.用户可以自己设置
    $condition = array(0=>'content-length-range', 1=>0, 2=>1048576000);
    $conditions[] = $condition;

    //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必须项,只是为了安全起见,防止用户通过policy上传到别人的目录
    $start = array(0=>'starts-with', 1=>'$key', 2=>$dir);
    $conditions[] = $start;


    $arr = array('expiration'=>$expiration,'conditions'=>$conditions);
    //echo json_encode($arr);
    //return;
    $policy = json_encode($arr);
    $base64_policy = base64_encode($policy);
    $string_to_sign = $base64_policy;
    $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

    $response = array();
    $response['accessid'] = $id;
    $response['host'] = $host;
    $response['policy'] = $base64_policy;
    $response['signature'] = $signature;
    $response['expire'] = $end;
    //这个参数是设置用户上传指定的前缀
    $response['dir'] = $dir;
    return $response;
}


function getMillisecond() {
    list($t1, $t2) = explode(' ', microtime());
    return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
}
function get_uuid() {
    $server_id = '001';
    $time = getMillisecond();
    $rand = rand(1000, 9999);
    $uuid = $time . $server_id.$rand;
    $id = Db::name("uuid")->insertGetId(['uuid' => $uuid]);
    $uuid = $uuid. $id;
    Db::name("uuid")->where('id', $id)->update(['uuid' => $uuid]);
    return $uuid;
}
function get_order_id() {
    $server_id = '001';
    $time = getMillisecond();
    $order_id = $time . $server_id;
    $id = Db::name("order_id")->insertGetId(['order_id' => $order_id]);
    $rand = rand(1000, 9999);
    $order_id = "h".$time . $server_id . $id;
    Db::name("order_id")->where('id', $id)->update(['order_id' => $order_id]);
    return $order_id;
}
function get_token() {
    $server_id = '001';
    $time = getMillisecond();
    $token = $time . $server_id;
    $id = Db::name("token_id")->insertGetId(['token' => $token]);
    $rand = rand(1000, 9999);
    $token = $time . $server_id . $id;
    Db::name("token_id")->where('id', $id)->update(['token' => $token]);
    return $token;
}
function get_ranks($desc=false){
    //获取最小等级
    $min_rank=Db::name("driver_rank_tree")->order('depth desc')->find();
    //获取列表
    $map['tr.son_id']=$min_rank['son_id'];
    $map['tr.parent_id']=array('neq',0);
    $m_driver_rank_tree=Db::name("driver_rank_tree")
        ->alias('tr')
        ->join('tp_driver_rank r',"r.id=tr.parent_id","left")
        ->join('driver_rank_tree tr2',"tr.parent_id=tr2.son_id and tr2.depth=1","left")
        ->where($map)
        ->field('r.*,tr2.parent_id');
        if($desc){

            $m_driver_rank_tree->order('tr.depth desc');
        }else{

            $m_driver_rank_tree->order('tr.depth asc');
        }
       $ranks= $m_driver_rank_tree->select();
    return $ranks;
}
function get_prank($son_id){

    $map['tr.depth']=1;
    $map['tr.son_id']=$son_id;
    $rank=Db::name("driver_rank_tree")
        ->alias('tr')
        ->join('tp_driver_rank r',"r.id=tr.parent_id","left")
        ->where($map)
        ->field('r.*,tr.parent_id')
        ->find();
    return $rank;
}
function get_srank($parent_id){
    $map['tr.depth']=1;
    $map['tr.parent_id']=$parent_id;
    $rank=Db::name("driver_rank_tree")
        ->alias('tr')
        ->join('tp_driver_rank r',"r.id=tr.son_id","left")
        ->where($map)
        ->field('r.*,tr.son_id')
        ->find();
    return $rank;
}

/*
 * 'driver_check_result 司导审核结果',
 *  'system_ordinary_info 系统普通消息',
 * 'news_order 新的订单',
 * 'checkouted 已经结算',
 * 'exam_pass 考试通过',
 * 'upgrade 升级',
 * 'driver_rank_apply 司机升级申请',
 *  'driver_degrade_appeal 司机降级申诉',
 * 'dispatch_traveler_group 旅客分组信息'
 * reset_group 重置订单状态
 * reject_settlement 结算不通过
 * @title set_info 录入消息
 * @param $data  type:array
 * return $infos type:int
 */
function set_info($user_id,$title,$content,$type="system_ordinary_info",$data=[]){
    $data['user_id']=$user_id;
    $data['title']=$title;
    $data['content']=$content;
    $data['create_time']=NOW_TIME;
    $data['type']=$type;

    switch ($type){
        case 'driver_check_result':
            $data['logo']="/static/index/img/msg_check.png";
         break;
        case 'news_order':
            $data['isorder']=true;
            $data['logo']="/static/index/img/msg_order.png";
            break;
        case 'reset_group':
        $data['logo']="/static/index/img/msg_order.png";
        $data['isorder']=true;
        break;

        case 'checkouted':
            $data['logo']="/static/index/img/msg_settlement.png";
            break;
        case 'upgrade':
            $data['logo']="/static/index/img/msg_check.png";
            break;
        case 'driver_rank_apply':
            $data['logo']="/static/index/img/msg_check.png";
            break;
        case 'dispatch_traveler_group':
            $data['logo']="/static/index/img/msg_order.png";
            $data['isorder']=true;
            break;
         case 'reject_settlement':
        $data['logo']="/static/index/img/msg_order.png";
             $data['isorder']=true;
        break;
        default:
            $data['logo']="/static/index/img/msg_sys.png";
    }
logs('notify-data',$data);
     $re = Db::name('notify')->strict(false)->insert($data);
    umeng_send($user_id,$title,$content);
    return $re;
}
function set_umeng_device($user_id,$data){
    if($data['device_type']){
        $map['device_type']=$data['device_type'];
    }
    Db::name('umeng_token')->where('user_id',$user_id)->where($map)->delete();
    $data['user_id']=$user_id;
    $re=Db::name('umeng_token')->insert($data);
    return $re;
}


function umeng_send($user_id,$title,$content){
    $ios_config['app_key']='5b3c8fe0f29d983bfd000046';
    $ios_config['secret']='nnpcn4vqhedcm2gctn95ceq16dfeaa8k';

    $android_config['app_key']='5b3c77e48f4a9d78fc00007c';
    $android_config['secret']='wsvsdous6nfskeoaestvx26asveyv7tc';
    $umeng_token=Db::name('umeng_token')
        ->where('user_id',$user_id)
        ->order('id desc')
        ->find();

    if(!$umeng_token){
        return false;
    }

    $device_token=$umeng_token['device_token'];
    if($umeng_token['device_type']=='ios'){
        $umeng=new \Umeng\Sms($ios_config['app_key'],$ios_config['secret']);
        $umeng->sendIOSUnicast($title,$content,$device_token);
    }else{
        $umeng=new \Umeng\Sms($android_config['app_key'],$android_config['secret']);
        $umeng->sendAndroidUnicast($title,$content,$device_token);
    }

}

function get_default_img($str, $just_path = FALSE) {
    if (!$str){
        return false;
    }
    $str_arr = explode(',', $str);
    $map['id'] = $str_arr[0];

    $re = Db::name('upload_file')->where($map)->find();

    if ($just_path && $re) {
        return $re['url'];
    }
    return $re;
}

/**
 * 获取图片集
 * @param $str
 * @return bool|mixed
 */
function get_img_array($str, $just_path = FALSE) {
    if (!$str)
        return false;
    $str_arr = @explode(',', $str);
    $map['id'] = array('in', $str_arr);
    if ($just_path) {
        return Db('upload_file')->where($map)->column('url');
    }
    return Db('upload_file')->where($map)->select();
}

//获取分组异常订单
function get_exceptional_order($group_id){
    $oids=Db::name("dispatch_traveler")->where("group_id",$group_id)->column('oid');
    $exceptional_orders=Db::name("exceptional_order")->where('oid','in',$oids)->where('solve',false)->select();
    return $exceptional_orders;
}


/**
 *  发送短信
 *
 */
function send_message($mobile, $content){
    $config = [
        'name'=>'18694047848',     //必填参数。用户账号
        'pwd'=>'9FA6EB4D075A98F84F896CF0D451',     //必填参数。（web平台：基本资料中的接口密码）
        'content'=> $content,   //必填参数。发送内容（1-500 个汉字）UTF-8编码
        'mobile'=>$mobile,   //必填参数。手机号码。多个以英文逗号隔开
        'stime'=>'',   //可选参数。发送时间，填写时已填写的时间发送，不填时为当前时间发送
        'sign'=>'青海精灵国旅',    //必填参数。用户签名。
        'type'=>'pt',  //必填参数。固定值 pt
        'extno'=>''    //可选参数，扩展码，用户定义扩展码，只能为数字
    ];
    //构造要post的字符串
    $flag = 0;
    $params='';//要post的数据
    foreach ($config as $index => $item) {
        if ($flag!=0) {
            $params .= "&";
            $flag = 1;
        }
        $params.= $index."="; $params.= urlencode($item);// urlencode($value);
        $flag = 1;
    }
    $url  = "http://web.wasun.cn/asmx/smsservice.aspx?".$params;
    $code = substr(file_get_contents($url), 0, 1);  //获取信息发送后的状态
    if($code == '0'){
        $msg['status'] = true;
        return $msg;
    }else{
        $msg['status'] = false;
        logs('send_message_code',$code);
        return $msg;
    }
}


/**
 *  截取字符串
 */
function truncate_utf8_string($string, $length, $etc = '...') {
    $result = '';
    $string = html_entity_decode ( trim ( strip_tags ( $string ) ), ENT_QUOTES, 'UTF-8' );
    $strlen = strlen ( $string );
    for($i = 0; (($i < $strlen) && ($length > 0)); $i ++) {
        if ($number = strpos ( str_pad ( decbin ( ord ( substr ( $string, $i, 1 ) ) ), 8, '0', STR_PAD_LEFT ), '0' )) {
            if ($length < 1.0) {
                break;
            }
            $result .= substr ( $string, $i, $number );
            $length -= 1.0;
            $i += $number - 1;
        } else {
            $result .= substr ( $string, $i, 1 );
            $length -= 0.5;
        }
    }
    $result = htmlspecialchars ( $result, ENT_QUOTES, 'UTF-8' );
    if ($i < $strlen) {
    $result .= $etc;
    }
    return $result;
}